package com.example.demo.buessiness.company.services;

import com.example.demo.buessiness.company.interfaces.ICompanyService;
import com.example.demo.buessiness.company.model.dto.CompanyRequest;
import com.example.demo.buessiness.company.model.po.Company;
import com.example.demo.buessiness.company.model.dto.CompanyResponse;
import com.example.demo.buessiness.company.repository.CompanyRepository;
import com.example.demo.buessiness.user.model.dto.UserResponse;
import com.example.demo.buessiness.user.model.po.User;
import lombok.extern.slf4j.Slf4j;
import msa.common.exception.IDataStorageException;
import msa.common.model.DataTableVO;
import msa.common.model.PageModel;
import msa.common.model.ResultCode;
import msa.common.model.ResultModel;
import msa.common.utils.DataTableConverter;
import msa.common.utils.IDGenerator;
import msa.common.utils.ResultModelUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class CompanyServiceImpl implements ICompanyService{

    @Autowired
    CompanyRepository companyRepository;

    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public ResultModel addCompany(CompanyRequest comRequest) {
        comRequest.setId(IDGenerator.getSnowflakeId());
        try{
            Company com = companyRepository.save(requestToPojo(comRequest));

            if(com == null){
                return ResultModelUtils.getSuccessInstance(pojoToResponse(com));
            }
            return ResultModelUtils.getAddSuccessInstance (true);
        }catch (Exception e){
            throw new IDataStorageException ("添加数据异常",e);
        }
    }
    //comRequest.setId(String.valueOf(IDGenerator.getSnowflakeId()));


    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public ResultModel updateCompany(CompanyRequest comRequest) {

        try {
            Company clients = requestToPojo (comRequest);
            companyRepository.save(clients);
            return ResultModelUtils.getEdiSuccessInstance (true);
        } catch (Exception e) {
            log.error ("修改公司异常",e);
            throw new IDataStorageException ("修改公司异常",e);
        }
    }

    //查询公司名
    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public List<CompanyResponse> findByCompany(String company) {
        List<Company> clients = companyRepository.findByCompany (company);
        return pojoLisToResponseList (clients);
    }


    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public ResultModel deleteCompany(Long id) {
        try {
            companyRepository.deleteById (id);
            return ResultModelUtils.getDelSuccessInstance (true);
        } catch (Exception e) {
            log.error ("删除公司异常",e);
            throw  new IDataStorageException ("删除公司异常",e);
        }
    }

    @Override
    public List<CompanyResponse> findAll() {
        List<Company> com = companyRepository.findAllByOrderByIdAsc();
        return pojoLisToResponseList(com);
    }


    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public void modifyCompanyByName(String address,Long id) {
       companyRepository.modifyCompanyByName(address,id);
    }

//    @Override
//    public List<companyResponse> findAllCompany() {
//        List<Company> company = companyRepository.findAllByOrderByIdAsc();
//        return pojoLisToResponseList (company);
//    }

    @Override
    public ResultModel findCompanyById(Long id){
        if(!companyRepository.existsById(id)){
            return ResultModelUtils.getFailInstance(ResultCode.PARAM_NULL.toString(),"未传递值");
        }
        Company company = companyRepository.findById(id).get();
        return ResultModelUtils.getSuccessInstance(pojoToResponse(company));
    }



    @Override
    public Company requestToPojo(CompanyRequest companyRequest) {
        Company com = new Company();
        BeanUtils.copyProperties(companyRequest,com);
        com.setId(companyRequest.getId());
        return com;
    }

    @Override
    public List requestListToPojoList(List<CompanyRequest> list) {
        return null;
    }

    public CompanyResponse pojoToResponse(Object o){
        CompanyResponse companyResponse = new CompanyResponse();
        Company company = (Company) o;
        BeanUtils.copyProperties(company,companyResponse);
        companyResponse.setId(company.getId());
        return companyResponse;
    }

    @Override
    public List<CompanyResponse> pojoLisToResponseList(List list) {
        if (CollectionUtils.isEmpty (list)) {
            return new ArrayList<> ();
        }
        List<CompanyResponse> responses = new ArrayList<> ();
        list.stream ().filter (client->client!=null).forEach (client->{
            responses.add (pojoToResponse (client));
        });
        return responses;

    }

    @Override
    public DataTableVO page(PageModel pageModel) {
        CompanyRequest request = (CompanyRequest)pageModel.getSearchData ();
        Page<Company> page = companyRepository.findAll((root, criteriaQuery, criteriaBuilder)-> {
            List<Predicate> predicates = new ArrayList<>();

            return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).orderBy (criteriaBuilder.asc (root.get ("time"))).getRestriction();
        },pageModel.getPageRequestInstance ());
        DataTableVO dataTableVO =  DataTableConverter.convert(page);
        List<Company> clients = page.getContent ();
        dataTableVO.setData (pojoLisToResponseList (clients));
        return dataTableVO;
    }
}